# encoding:utf-8
"""
@file = power_manage
@author = zouju
@create_time = 2023-09-13- 11:09
"""
import json

from django.shortcuts import render
from rest_framework.decorators import api_view

from common.API import res_josn_data
from common.API.log import exec_log
from common.authentication.jwt_auth import jwt_login_required
from common.layuiview.layuiviewsets import ModelViewSetLayui
from system_manage.models import Power, RolePower
from system_manage.serializers import PowerModelSerializer


def power_manage_page(request):
    return render(request, 'sys_manage/power_manage/power_main.html')


def power_add_page(request):
    return render(request, 'sys_manage/power_manage/power_add.html')


@api_view(['POST'])
@jwt_login_required
def power_sub_query(request):
    if request.method == 'POST':
        data_list = []
        post_data = request.POST
        print('请求数据:', post_data)
        type_value = post_data['type_value']
        if type_value == '1':
            return res_josn_data.table_api(data=[])
        else:
            power_obj = Power.objects.filter(type=1).all()

            for item in power_obj:
                item_data = {
                    "power_id": item.id,
                    "power_name": item.name
                }
                data_list.append(item_data)
            return res_josn_data.table_api(data=data_list, count=len(power_obj))


class PowerGenericView(ModelViewSetLayui):  # 权限视图
    queryset = Power.objects.all()
    serializer_class = PowerModelSerializer

    def list(self, request, *args, **kwargs):
        '''
        重写list方法, type_id字段查询时包含因__icontains时报错,修改为__exact
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''
        page = request.GET.get('page', 1)
        limit = request.GET.get('limit', 10)
        post_data_str = request.GET.get('Params', None)
        number = (int(page) - 1) * int(limit)  # 每页开始的序号
        filters = {}

        if post_data_str is None:
            return res_josn_data.table_api(count=0, data=[])
        json_data = json.loads(post_data_str)
        for k, v in json_data.items():
            if v not in (None, ''):
                if k in ['type_id', 'parent_id']:
                    db_field = k + '__exact'
                    filters[db_field] = v
                else:
                    db_field = k + '__icontains'
                    filters[db_field] = v
        print('filters:', filters)
        queryset = self.get_serializer_class().Meta.model.objects.filter(**filters).order_by('-id')  # 过滤
        page = self.paginate_queryset(queryset)  # 分页
        serializer = self.get_serializer(queryset, many=True)  # 序列化

        if page is None:
            return
        else:
            serializer_page = self.get_serializer(page, many=True)
            return res_josn_data.table_api(count=len(serializer.data), data=serializer_page.data, number=number)

    def create(self, request, *args, **kwargs):
        '''
        重写create方法，自动添加权限到role_power表, role_id值默认为1(管理员)
        '''
        print('request.data:', request.data)
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            validated_data = serializer.validated_data
            validated_data['type_id'] = int(request.data['type_id'])
            # print(validated_data)
            serializer.save()
            exec_log(request, is_access=True, desc=dict(validated_data))
        max_obj = Power.objects.all().order_by('-id').first()
        role_power_obj = RolePower(role_id=1, power_id=max_obj.id,  power_type_id=int(request.data['type_id']))
        role_power_obj.save()
        return res_josn_data.table_success(msg='创建成功', data=serializer.data)